package com.fastjrun.security.authentication;

import com.fastjrun.security.utils.HttpRequestUtils;
import com.fastjrun.share.demo.dao.LogRecordDao;
import com.fastjrun.share.demo.entity.LogRecord;
import com.fastjrun.share.demo.entity.SysUser;
import com.fastjrun.share.demo.security.vo.UserDetailsVO;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component("customAuthenticationSuccessListener")
public class CustomAuthenticationSuccessListener implements AuthenticationSuccessListener {
  @Resource LogRecordDao logRecordDao;

  @Override
  public void successListener(
      HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

    UserDetailsVO userDetails = (UserDetailsVO) (authentication.getPrincipal());
    SysUser sysUser = userDetails.getSysUser();
    LogRecord logRecord = new LogRecord();
    logRecord.setUserId(sysUser.getId());
    logRecord.setUsername(sysUser.getUsername());
    logRecord.setMobile(sysUser.getMobile());
    logRecord.setEmail(sysUser.getEmail());
    logRecord.setLoginTime(new Date());
    logRecord.setUserAgent(HttpRequestUtils.retriveUserAgent(request));
    logRecord.setLoginIp(HttpRequestUtils.retriveIP(request));

    logRecordDao.insert(logRecord);
  }
}
